import { TypographyTitle } from '@/components/Typography';
import { AutoComplete, Button, Empty, Input } from 'antd';
import cls from 'classnames';
import { ChangeEvent, useContext, useMemo, useState } from 'react';
import { ResourcesContext } from '../hooks';
import { IResourceRangeRightSearch } from '../type';
import {
  SearchOutlined,
  PlusOutlined,
  ReloadOutlined,
} from '@ant-design/icons';
import { ResourRangeContext } from '../hooks/useResourRangeContext';
import { loopArray } from '@/utils';
import { ResourRangeAddModal } from './ResourRangeAddModal';

export const ResourceRangeRightSearch: React.FC<IResourceRangeRightSearch> = ({
  dataSource,
}) => {
  const { prefixCls, resourCurrent } = useContext(ResourcesContext);
  const {
    searchTableValue,
    resRangeDispatch,
    reloadTableDataSource,
    selectKeys,
    treeLoading,
  } = useContext(ResourRangeContext);

  const [showRangeModal, setShowRangeModal] = useState<boolean>(); //是否打开新增弹框
  const openRangeModal = (isFalse: boolean) => {
    setShowRangeModal(isFalse);
  };

  // 搜索下拉菜单
  const autoOption = useMemo(() => {
    let option: Record<string, any>[] = [];
    const tileTreeData = (data: Record<string, any>[]) => {
      data?.forEach((item) => {
        if (item?.children && item?.children?.length > 0) {
          tileTreeData(item?.children);
        }
        if (item?.name?.includes(searchTableValue)) {
          // const name = item?.name;
          // const nameLength = name?.length;
          // const select = name?.search(searchTableValue);
          // const searchLength = searchTableValue?.length;
          // const afterStr = name?.slice(0, select);
          // const selectStr = searchTableValue;
          // const beforeStr = name?.slice(select + searchLength, nameLength);
          option.push({
            value: item?.name,
            key: item?.id,
            // label: (
            //   <div>
            //     <span>{afterStr}</span>
            //     <span style={{ color: '#f50' }}>{selectStr}</span>
            //     <span>{beforeStr}</span>
            //   </div>
            // ),
          });
        }
      });
    };
    tileTreeData(dataSource);

    return option;
  }, [dataSource, searchTableValue]);

  // 搜索框改变
  const onInputChange = (e: ChangeEvent<HTMLInputElement>) => {
    resRangeDispatch({
      type: 'range-searchTableValue',
      payload: e.target.value,
    });
  };

  // 点击搜索
  const onAutoSelect = (value: string, option: any) => {
    const promise = new Promise((resolve, reject) => {
      const optionId = option?.key;
      const targetNode = loopArray(dataSource)?.find((i) => i?.id === optionId);
      resRangeDispatch({
        type: 'range-expandedRowKeys',
        // payload: [option?.key],
        payload: [targetNode?.pID],
      });

      resRangeDispatch({
        type: 'range-searchTableValue',
        payload: value,
      });

      // resRangeDispatch({
      //   type: 'range-checkedRowKeys',
      //   payload: [targetNode?.id]
      // })

      // resRangeDispatch({
      //   type: 'range-expandedKeys',
      //   payload: [targetNode?.pID],
      // });
      // resRangeDispatch({
      //   type: 'range-autoExpandParent',
      //   payload: true,
      // });

      setTimeout(() => {
        scrollToAnchor(optionId);
      }, 1000);

      resolve(optionId);
    });
    promise.then((res: any) => {
      if (res) {
        // reloadTableDataSource(res);
      }
    });
  };

  // 滚动定位
  const scrollToAnchor = (id: string) => {
    let anchorElement = document.getElementById(id);
    if (id) {
      anchorElement?.scrollIntoView({ block: 'start', behavior: 'smooth' });
    }
  };

  return (
    <>
      <div className={cls(prefixCls + 'table-header')}>
        <TypographyTitle
          level={4}
          style={{
            margin: 0,
          }}
        >
          {resourCurrent == 1 && '数据范围'}
          {resourCurrent == 2 && '功能操作'}
        </TypographyTitle>
        <div className={cls(prefixCls + 'table-search')}>
          {/* <Input
            placeholder={'请按名称搜索'}
            // ref={searchRef}
            allowClear
            // onPressEnter={onSearch}
            suffix={<SearchOutlined />}
            addonAfter={
              <ReloadOutlined
              // onClick={() => reloadTableDataSource(selectKeys?.[0])}
              />
            }
          /> */}
          <AutoComplete
            style={{
              width: 400,
            }}
            options={autoOption}
            onSelect={onAutoSelect}
            notFoundContent={<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
          >
            <Input
              placeholder={'请按名称搜索'}
              suffix={<SearchOutlined />}
              onChange={onInputChange}
              addonAfter={
                <ReloadOutlined
                  onClick={() => {
                    resRangeDispatch({
                      type: 'range-searchTableValue',
                      payload: '',
                    });
                    resRangeDispatch({
                      type: 'range-expandedRowKeys',
                      payload: [],
                    });
                    reloadTableDataSource(selectKeys?.[0]);
                  }}
                />
              }
              allowClear
            />
          </AutoComplete>
          <Button
            type={'primary'}
            icon={<PlusOutlined />}
            onClick={() => {
              openRangeModal(true);
            }}
            style={{
              marginLeft: 12,
            }}
            disabled={treeLoading}
          >
            添加
          </Button>
        </div>
      </div>

      {showRangeModal && (
        <ResourRangeAddModal
          onClose={() => {
            openRangeModal(false);
          }} //取消弹框
          pIdData={dataSource} //上级资源 pID字段数据源
          // editAddRows={{ detaID: expandedRowKeys?.length > 0 ? expandedRowKeys?.toString() : '' }}  //选中表格,默认为上级资源
          editAddRows={{}} //选中表格,默认为上级资源
          visible={showRangeModal}
          modalType={'add'}
        />
      )}
    </>
  );
};
